﻿using System;
using System.Linq;
using System.IO;

namespace QLab.Controllers.SolutionExplorer
{

	public class SolutionExplorerItemFile : SolutionExplorerItemBase
	{

		protected string _buffer = "";
		protected bool _changed = false;

		public SolutionExplorerItemFile()
			: base(SolutionExplorerItemType.Q_File) { }

		public string Buffer
		{
			get { return _buffer; }
			set
			{
				_buffer = value;
				_changed = true;
			}
		}
		public bool Changed { get { return _changed; } }


		public override void Load(string Path)
		{
			throw new System.NotImplementedException();
		}

		public override void Save()
		{
			try
			{
				// Create the file if not exists.
				if (!System.IO.File.Exists(FullPath))
					System.IO.File.Create(FullPath).Close();

				if (_changed)
				{
					if (IO.Files.CustomFile.SaveText(FullPath, _buffer))
						_changed = false;
					else
					{
						// Error message
					}
				}
			}
			catch /* (System.Exception e ) */
			{
				// Error message
			}
		}

		public override void Remove()
		{
			if (this.ChildItems != null && this.ChildItems.Count > 0)
			{
				foreach (SolutionExplorerItemBase child in ChildItems.ToArray())
					child.Remove();
			}

			FileInfo fi = new FileInfo(FullPath);
			if (fi.Exists)
			{
				try
				{
					fi.Delete();
				}
				catch (Exception e)
				{
					Console.WriteLine(e.ToString());
				}
			}

			if (Parent != null)
				Parent.ChildItems.Remove(this);
		}
	}
}
